const { HotModuleReplacementPlugin } = require("webpack");
const { merge } = require("webpack-merge");
const path = require("path");
const fs = require("fs");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackBar = require("webpackbar");
let port = undefined
if (fs.existsSync(path.resolve(process.cwd(), 'pack.config.js'))) {
  const packConfig = require(path.resolve(process.cwd(), 'pack.config.js'))
  console.log('packConfig',{packConfig})
  port = packConfig.port
}
const common = require("./webpack.common");

const tsLoader = common.module.rules.find((r) => r.loader === "ts-loader");
if (tsLoader) {
  tsLoader.options = {
    ...tsLoader.options,
    // getCustomTransformers: () => ({
    //   before: [ReactRefreshTypeScript()],
    // }),
    transpileOnly: true,
  };
}

// console.log("sssssssss", process.env);
module.exports = merge(common, {
  mode: "development",
  devtool: "cheap-module-source-map",
  devServer: {
    port,
    headers: { "Access-Control-Allow-Origin": "*" },
    allowedHosts: "all",
    onBeforeSetupMiddleware: function (devServer) {
      // if (!devServer) {
      //   throw new Error('webpack-dev-server is not defined');
      // }

      devServer.app.get("/index", (_, res) => {
        res.send("this is an app");
      });
    },
    historyApiFallback: true,
    client: {
      overlay: false,
    },
    static: {
      directory: path.resolve(process.cwd(), "./public"),
    },
  },
  plugins: [
    new HotModuleReplacementPlugin(),
    // new ReactRefreshWebpackPlugin(),
    // new HtmlWebpackPlugin({
    //   filename: path.resolve(__dirname, '../dist/index.html'),
    //   template: path.resolve(__dirname, `../public/index.html`),
    //   templateParameters: {
    //     entryPath: `/entry.js`,
    //   },
    //   inject: false, // @todo 'body',
    //   // templateContent: {}, // function() {}
    // }),
    // new CleanTerminalPlugin(),
    new WebpackBar(),
  ],
});
